package cn.wsn2018.tools.ctrl;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.model.Log.ErrorLogInfo;
import cn.wsn2018.tools.model.Log.WarningLogInfo;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.service.LogsInfoService;
import cn.wsn2018.tools.util.*;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.OutputStream;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gmz.
 * @date 2018/12/14.
 * @time 20:50
 */
@RestController
@RequestMapping("/protocol")
public class LogsInfoController {
    private Logger logger = Logger.getLogger(LogsInfoController.class);

    @Autowired
    private LogsInfoService logsInfoService;

    /**
     * 分页查询，默认以createTime降序排列，查询所有日志信息
     * @param request
     * @param response
     * @throws Exception
     */

    @CrossOrigin
    @RequestMapping(value = "/logsInfo",method = RequestMethod.GET)
    public void findAllLogs(@RequestParam("username")String username,
                            @RequestParam("eventType")Integer eventType,
                            @RequestParam("pageNum")String pageNum,
                            @RequestParam("pageSize")String pageSize,
                            @RequestParam("fromTime")String fromTime,
                            @RequestParam("toTime")String toTime,
                            @RequestParam("token") String token,
                            @RequestParam("timeSort")String timeSort,
                            @RequestParam("eventTypeSort")String eventTypeSort,
                            @RequestParam("usernameSort")String usernameSort,
                            @RequestParam("typeSort")String typeSort,
                            @RequestParam("click")Boolean click,
                            HttpServletRequest request, HttpServletResponse response) throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myRole = session.getAttribute("role").toString();
        String myUsername = session.getAttribute("username").toString();
        if(CommonValue.ROLE_AUDITOR.equals(myRole)){
            String json = logsInfoService.findLogsByCond(username,eventType,pageNum,pageSize,fromTime,toTime,timeSort,usernameSort,typeSort,eventTypeSort,myUsername,click);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            LogUtil.produceWarningLogs(username,
                    CommonValue.WARNING_TYPE_1,
                    CommonValue.WARNING_LEVEL_0,
                    CommonValue.AUDITOR_MODULE,
                    ServletUtil.getClientIp(request),
                    LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,username,RoleUtil.getRoleName(myRole),CommonValue.AUDITOR_MODULE)
            );
            ServletUtil.getInstance().responseOperating(response, json);
        }
    }

    /**
     * @Description: 分页查询错误日志的接口
     * @Param: [username, pageNum, pageSize, fromTime, toTime, token, request, response]
     * @return: void
     * @Author: SongDaisong
     * @Date: 21:12
     */
    @CrossOrigin
    @RequestMapping(value = "/listErrorLogInfo",method = RequestMethod.GET)
    public void listErrorLogInfo(@RequestParam("username") String username,
                                 @RequestParam("pageNum") String pageNum,
                                 @RequestParam("pageSize") String pageSize,
                                 @RequestParam("fromTime") String fromTime,
                                 @RequestParam("toTime") String toTime,
                                 @RequestParam("token") String token,
                                 @RequestParam("errorModuleSort")String errorModuleSort,
                                 @RequestParam("errorUsernameSort")String errorUsernameSort,
                                 @RequestParam("errorTimeSort")String errorTimeSort,
                                 @RequestParam("typeSort")String operatTypeSort,
                                 @RequestParam("click")Boolean click,
                                 HttpServletRequest request, HttpServletResponse response)throws Exception{

        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myRole = session.getAttribute("role").toString();
        String myUsername = session.getAttribute("username").toString();

        if(CommonValue.ROLE_SYS_AUDITOR.equals(myRole)){
            String json = logsInfoService.listLogInfo( username,pageNum, pageSize, fromTime, toTime,ErrorLogInfo.class,"errorLogInfo",
                    null,null,null,
                    errorTimeSort,errorModuleSort,errorUsernameSort,operatTypeSort,click,myUsername);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            LogUtil.produceWarningLogs(username,
                    CommonValue.WARNING_TYPE_1,
                    CommonValue.WARNING_LEVEL_0,
                    CommonValue.SYS_AUDITOR_MODULE,
                    ServletUtil.getClientIp(request),
                    LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,username,RoleUtil.getRoleName(myRole),CommonValue.SYS_AUDITOR_MODULE));
            ServletUtil.getInstance().responseOperating(response, json);
        }



    }

    /**
     * @Description: 分页查询告警日志的接口
     * @Param: [username, pageNum, pageSize, fromTime, toTime, token, request, response]
     * @return: void
     * @Author: SongDaisong
     * @Date: 21:12
     */
    @CrossOrigin
    @RequestMapping(value = "/listWarningLogInfo",method = RequestMethod.GET)
    public void listWarningLogInfo(@RequestParam("username") String username,
                                   @RequestParam("pageNum") String pageNum,
                                   @RequestParam("pageSize") String pageSize,
                                   @RequestParam("fromTime") String fromTime,
                                   @RequestParam("toTime") String toTime,
                                   @RequestParam("token") String token,
                                   @RequestParam("moduleNameSort")String moduleNameSort,
                                   @RequestParam("warnTypeSort")String warnTypeSort,
                                   @RequestParam("warnLevelSort")String warnLevelSort,
                                   @RequestParam("warnTimeSort")String warnTimeSort,
                                   @RequestParam("usernameSort")String usernameSort,
                                   @RequestParam("click")Boolean click,
                                   HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myRole = session.getAttribute("role").toString();
        String myUsername = session.getAttribute("username").toString();
        if(CommonValue.ROLE_SYS_AUDITOR.equals(myRole)){
            String json = logsInfoService.listLogInfo(username, pageNum, pageSize, fromTime, toTime,
                    WarningLogInfo.class,"warningLogInfo",moduleNameSort,warnTypeSort,warnLevelSort,warnTimeSort,
                    null,usernameSort,null,click,myUsername);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            LogUtil.produceWarningLogs(username,
                    CommonValue.WARNING_TYPE_1,
                    CommonValue.WARNING_LEVEL_0,
                    CommonValue.SYS_AUDITOR_MODULE,
                    ServletUtil.getClientIp(request),
                    LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,username,RoleUtil.getRoleName(myRole),CommonValue.SYS_AUDITOR_MODULE));
            ServletUtil.getInstance().responseOperating(response, json);
        }

    }

    /**
     * 一键下载日志功能
     * @param token
     * @param request
     * @param response
     * @throws Exception
     */
    @CrossOrigin
    @RequestMapping(value = "/storesLog",method = RequestMethod.GET)
    public void storesLog(@RequestParam("token")String token,@RequestParam("username") String username,
                          @RequestParam("type") String type,HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myRole = session.getAttribute("role").toString();
        //双重身份判断
        if(
                (CommonValue.ROLE_SYS_AUDITOR.equals(myRole)&&("warn".equals(type)||"error".equals(type)))
                ||(CommonValue.ROLE_AUDITOR.equals(myRole)&&"normal".equals(type))
        ){
            //系统审计员只能下载告警或者错误日志
            //业务审计员只能下载业务日志
            String filename="target.xlsx";
            if(type.equals("warn")){
                filename="warningLog.xlsx";
            }
            else if(type.equals("error")){
                filename="errorLog.xlsx";
            }
            else if(type.equals("normal")){
                filename="businessLog.xlsx";
            }
            filename = new String(filename.getBytes(),"ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ filename);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            SXSSFWorkbook workbook  = logsInfoService.storeLogsInfo(username,type);
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        }else {
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            if("normal".equals(type)){
                //业务日志模块越权
                LogUtil.produceWarningLogs(username,
                        CommonValue.WARNING_TYPE_1,
                        CommonValue.WARNING_LEVEL_0,
                        CommonValue.AUDITOR_MODULE,
                        ServletUtil.getClientIp(request),
                        LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,username,RoleUtil.getRoleName(myRole),CommonValue.AUDITOR_MODULE));
            }else if("warn".equals(type)||"error".equals(type)){
                //系统审计模块越权
                LogUtil.produceWarningLogs(username,
                        CommonValue.WARNING_TYPE_1,
                        CommonValue.WARNING_LEVEL_0,
                        CommonValue.SYS_AUDITOR_MODULE,
                        ServletUtil.getClientIp(request),
                        LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,username,RoleUtil.getRoleName(myRole),CommonValue.SYS_AUDITOR_MODULE));
                ServletUtil.getInstance().responseOperating(response, json);
            }
        }
    }


    /**
     * @Description: 统计业务日志信息
     * @Param: [fromTime, toTime, name, token, eventType, request, response]
     * @return: void
     * @Author: SongDaisong
     * @Date:  2020/2/21 16:08
     */
    @CrossOrigin
    @RequestMapping(value = "/statiscal",method = RequestMethod.GET)
    public void statisticalBusLogs(@RequestParam("fromTime") String fromTime,
                                   @RequestParam("toTime") String toTime,
                                   @RequestParam("name") String name,
                                   @RequestParam("token") String token,
                                   @RequestParam("eventType") Integer eventType,
                                   HttpServletRequest request,HttpServletResponse response) throws Exception {

        String msg = logsInfoService.statisticalBusLogs(fromTime, toTime, name,eventType,token, request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }


    /**
     * @Description: 统计告警日志
     * @Param: [fromTime, toTime, name, token, warnType, request, response]
     * @return: void
     * @Author: SongDaisong
     * @Date:  2020/3/4 11:44
     */
    @CrossOrigin
    @RequestMapping(value = "/wStatiscal",method = RequestMethod.GET)
    public void statisticalWarnLogs(@RequestParam("fromTime") String fromTime,
                                    @RequestParam("toTime") String toTime,
                                    @RequestParam("name") String name,
                                    @RequestParam("token") String token,
                                    @RequestParam("warnType") Integer warnType,
                                    HttpServletRequest request,HttpServletResponse response)throws Exception {

        String msg = logsInfoService.statisticalWarnLogs(fromTime, toTime, name, warnType, token, request);
        ServletUtil.getInstance().responseOperating(response,msg);

    }

    /**
     * @Description: 统计错误日志
     * @Param: [fromTime, toTime, name, token, moduleType, request, response]
     * @return: void
     * @Author: SongDaisong
     * @Date:  2020/3/4 11:44
     */
    @CrossOrigin
    @RequestMapping(value = "/eStatiscal",method = RequestMethod.GET)
    public void statisticalErrorLogs(@RequestParam("fromTime") String fromTime,
                                    @RequestParam("toTime") String toTime,
                                    @RequestParam("name") String name,
                                    @RequestParam("token") String token,
                                    @RequestParam("moduleType") Integer moduleType,
                                    HttpServletRequest request,HttpServletResponse response)throws Exception {

        String msg = logsInfoService.statisticalErrorLogs(fromTime, toTime, name, moduleType, token, request);
        ServletUtil.getInstance().responseOperating(response,msg);

    }


    @CrossOrigin
    @RequestMapping(value = "/getuserlogarrivedmax",method = RequestMethod.GET)
    public void getUserLogArrivedMaxVolume(@RequestParam("token") String token,
                                           @RequestParam("timeStamp")String timeStamp,
                                           HttpServletRequest request,HttpServletResponse response) throws Exception {
        /** 
        * @Description: 查询本地业务日志文件是否即将达到上限
        * @Param: [token, timeStamp, request, response] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/4/17 16:58
        */ 
        String msg=logsInfoService.getUserLogArrivedMax(token,request);
        ServletUtil.getInstance().responseOperating(response,msg);

    }

    @CrossOrigin
    @RequestMapping(value = "/getwarnlogarrivedmax",method = RequestMethod.GET)
    public void getWarnLogArrivedMaxVolume(@RequestParam("token") String token,
                                           @RequestParam("timeStamp")String timeStamp,
                                           HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
         * @Description: 查询本地业务日志文件是否即将达到上限
         * @Param: [token, timeStamp, request, response]
         * @return: void
         * @Author: SongDaisong
         * @Date:  2020/4/17 16:58
         */
        if(!CheckUserTimeStamp.isValidateQuery(token,timeStamp)){
            //如果用户两次请求时间太短，就不允许执行
            return;
        }
        String msg=logsInfoService.getWarnLogArrivedMax(token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/geterrorlogarrivedmax",method = RequestMethod.GET)
    public void getErrorLogArrivedMaxVolume(@RequestParam("token") String token,
                                           @RequestParam("timeStamp")String timeStamp,
                                           HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
         * @Description: 查询本地业务日志文件是否即将达到上限
         * @Param: [token, timeStamp, request, response]
         * @return: void
         * @Author: SongDaisong
         * @Date:  2020/4/17 16:58
         */
        if(!CheckUserTimeStamp.isValidateQuery(token,timeStamp)){
            //如果用户两次请求时间太短，就不允许执行
            return;
        }
        String msg=logsInfoService.getErrorLogArrivedMax(token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

}
